<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 
 * Config Model
 */
class Config_model extends MY_Model
{
    
    
    public function __construct() {
        parent::__construct();
        $this->primary_key = 'key';
    }
    
    public function get_config($key=null){
        $configs = $this->get_all();
        if ($key){
           $config = array();
           if (isset($_COOKIE['_m_config'])){
               $config = json_decode($_COOKIE['_m_config'], true);
               return $config[$key];
           }else{
               foreach ($configs as $value) {
                   $config[$value->key]=$value->value;
               }
               setcookie(
                '_m_config',
                json_encode($config),
                0,
                "/",
                null, //domain
                true, // Secure
                true); // httponly, no need in jS
               return $config[$key];
           }
        }
        return $configs;
    }
    
    
    
    /**
     * This method will purely update 
     * 
     * @param array $datas
     * @return boolean
     * @throws Exception
     */
    public function save($configs= array()){
        log_message('debug',  print_r($configs, true));
        try{
            foreach($configs as $key => $value){
                $this->update($key, array('value'=>$value));
            }
            return true;
        }catch (Exception $e){
            throw new Exception("Updating config failed");
        }
        return false;
    }
   
}